package com.daffodil.devtool.service.impl;

import java.util.Date;
import java.util.List;

import com.daffodil.core.entity.HqlHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.daffodil.core.dao.JpaDao;
import com.daffodil.core.entity.Query;
import com.daffodil.devtool.entity.GenTableColumn;
import com.daffodil.devtool.service.IGenTableColumnService;
import com.daffodil.framework.exception.BaseException;
import com.daffodil.util.StringUtils;

/**
 * 业务字段 服务层实现
 * @author yweijian
 * @date 2020年5月13日
 * @version 1.0
 */
@Service
public class GenTableColumnServiceImpl implements IGenTableColumnService {
    
    @Autowired
    private JpaDao<String> jpaDao;

    @Override
    public List<GenTableColumn> selectGenTableColumnList(Query<GenTableColumn> query) {
        HqlHelper helper = HqlHelper.of("from GenTableColumn where 1=1", query).withTimeRange().withOrder().build();
        return jpaDao.search(helper.getHql().toString(), helper.getParas(), GenTableColumn.class, query.getPage());
    }

    @Override
    @Transactional
    public void insertGenTableColumn(List<GenTableColumn> tableColumns) {
        if(StringUtils.isNotEmpty(tableColumns)) {
            String tableId = tableColumns.get(0).getTableId();
            if(StringUtils.isEmpty(tableId)) {
                throw new BaseException("数据库表ID不能为空");
            }
            jpaDao.delete("delete from GenTableColumn where tableId = ?", tableId);
            for (int i = 0; i < tableColumns.size(); i++) {
                GenTableColumn tableColumn = tableColumns.get(i);
                tableColumn.setId(null);
                tableColumn.setTableId(tableId);
                tableColumn.setSort(i+1);
                tableColumn.setCreateTime(new Date());
                jpaDao.save(tableColumn);
            }
        }
    }

}